package com.zqh.myfmmall.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zqh.myfmmall.constants.RedisExpireTime;
import com.zqh.myfmmall.dao.IndexImgDao;
import com.zqh.myfmmall.entity.IndexImg;
import com.zqh.myfmmall.redis.RedisUtil;
import com.zqh.myfmmall.result.Result;
import com.zqh.myfmmall.service.IndexImgService;
import net.sf.jsqlparser.statement.create.table.Index;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 轮播图 (IndexImg)表服务实现类
 *
 * @author KONO 曾淇杭哒！
 * @since 2022-01-20 20:52:59
 */
@Service("indexImgService")
public class IndexImgServiceImpl extends ServiceImpl<IndexImgDao, IndexImg> implements IndexImgService {
    @Autowired
    private RedisUtil redisUtil;
    @Override
    public Result listIndextImages() {
        List<IndexImg> indexImgs = null;
        Result result = null;
        indexImgs = ((List<IndexImg>) redisUtil.get("indexImgs"));
        //一级缓存不为空
        if (indexImgs != null) {
            result = Result.success(indexImgs);
            //二级缓存配合redis分布式锁解决缓存击穿问题
        }else{
            indexImgs = ((List<IndexImg>) redisUtil.get("indexImgs-backup"));
            if (indexImgs != null) {
                //使用缓存备份作为数据返回
                result = Result.success(indexImgs);
                //添加更新categories缓存的锁，从而只启动一个线程来更新缓存
                boolean isAbsent = redisUtil.setnx("indexImgs-lock","1");
                if (isAbsent) {
                    List<IndexImg> indexImagesList = query().list();
                    redisUtil.set("indexImgs",indexImagesList,
                            RedisExpireTime.INDEXPICTURE.getTime(),RedisExpireTime.INDEXPICTURE.getTimeUnit());
                    redisUtil.set("indexImgs-backup",indexImagesList,
                            RedisExpireTime.INDEXPICTURE.getTime() + 3,RedisExpireTime.INDEXPICTURE.getTimeUnit());
                    //释放锁
                    redisUtil.del("indexImgs-lock");
                }
                //初始categories-list和categories-list-backup缓存数据(即第一次访问时进行)，但是这里可以通过缓存预热来优化，暂时先这样写
            }else{
                List<IndexImg> indexImagesList = query().list();
                redisUtil.set("indexImgs",indexImagesList,
                        RedisExpireTime.INDEXPICTURE.getTime(),RedisExpireTime.INDEXPICTURE.getTimeUnit());
                redisUtil.set("indexImgs-backup",indexImagesList,
                        RedisExpireTime.INDEXPICTURE.getTime() + 3,RedisExpireTime.INDEXPICTURE.getTimeUnit());
                result = Result.success(indexImagesList);
            }
        }
        return result;
    }
}

